package com.wish233.wrpcspringbootstarter.boostrap;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.wish233.application.RpcApplication;
import com.wish233.config.RegistryConfig;
import com.wish233.config.RpcConfig;
import com.wish233.model.register.ServiceMetaInfo;
import com.wish233.register.Registry;
import com.wish233.register.factory.RegistryFactory;
import com.wish233.register.local.LocalServiceRegister;
import com.wish233.wrpcspringbootstarter.annotation.WrpcService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * @author WHH
 */
public class RpcProviderBootStrap implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        WrpcService wrpcService = beanClass.getAnnotation(WrpcService.class);
        if (wrpcService != null) {
            //配置服务基本信息
            Class<?> serviceClass = wrpcService.serviceClass();
            //处理默认值
            if (serviceClass == void.class) {
                serviceClass = beanClass.getInterfaces()[0];
            }
            String serviceName = serviceClass.getName();
            String version = wrpcService.version();
            //本地注册
            LocalServiceRegister.registerService(serviceName, beanClass);
            ((Logger) LoggerFactory.getLogger("io.grpc.netty")).setLevel(Level.INFO);
            // 注册服务到注册中心
            RpcConfig rpcConfig = RpcApplication.getRpcConfig();
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceVersion(version);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException("服务:" + serviceName + " 实现类:" + serviceClass.getName() + "注册失败！", e);
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
